package com.lmc.health.rate;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lmc.entity.HeartRate;
import com.lmc.entity.HeartType;
import com.lmc.health.HealthDataInfoActivit;
import com.lmc.R;
import com.lmc.adapter.DataListAdapter;
import com.lmc.entity.HealthData;
import com.lmc.util.DateFormatUtil;
import com.lmc.util.JsonManager;
import com.lmc.view.GridViewForScrollView;
import com.qxzn.app.api.api.HttpRequest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 心率数据每天的数据
 */
public class DataFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener {
    private ImageView left;
    private TextView month_tv;
    private ImageView right;
    private GridViewForScrollView grid_view;
    private ImageView iv1;
    private TextView value, value2;
    private TextView time, time2;
    private TextView unit, unit2;
    private List<HealthData> list = new ArrayList<>();
    private DataListAdapter adapter;
    private RelativeLayout data_info_1, data_info_2;
    private int month = 1;//月份
    private int years = 2020;//年份

    private HeartRate.DataBean.ResultBean select_data, select_dat2;//选择的那一天的数据
    private HeartRate heartRate;//30天的总数据

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.lmc_fragment_data, container, false);

        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        adapter = new DataListAdapter(getContext(), list);
        grid_view.setAdapter(adapter);
        grid_view.setOnItemClickListener(this);
        data_info_1.setOnClickListener(this);
        data_info_2.setOnClickListener(this);
        left.setOnClickListener(this);
        right.setOnClickListener(this);
        initData();
        Get();
    }

    private void initData() {
        Calendar calendar = Calendar.getInstance();
        years = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
    }

    private void initView(View view) {
        left = (ImageView) view.findViewById(R.id.left);
        month_tv = (TextView) view.findViewById(R.id.month_tv);
        right = (ImageView) view.findViewById(R.id.right);
        grid_view = (GridViewForScrollView) view.findViewById(R.id.grid_view);
        iv1 = (ImageView) view.findViewById(R.id.iv1);
        value = (TextView) view.findViewById(R.id.value);
        time = (TextView) view.findViewById(R.id.time);
        data_info_1 = view.findViewById(R.id.data_info_1);
        unit = view.findViewById(R.id.unit);
        value2 = view.findViewById(R.id.value2);
        unit2 = view.findViewById(R.id.unit2);
        time2 = view.findViewById(R.id.time2);
        data_info_2 = view.findViewById(R.id.data_info_2);
    }


    private void Get() {
        //后台要求先请求获取测量类型
        month_tv.setText(month + "月");
        final HeartRateActivity activity = (HeartRateActivity) getActivity();


        JSONObject params = new JSONObject();
        params.put("device_id", activity.health.getDevice_id());
        params.put("username", activity.health.getUsername());
        params.put("datetime", getDataTime());
        params.put("type", activity.health.getTname());
        Log.e("-----------", "device_id:" + activity.health.getDevice_id());
        Log.e("-----------", "username:" + activity.health.getUsername());
        Log.e("-----------", "datetime:" + getDataTime());
        Log.e("-----------", "type:" + activity.health.getTname());
        HttpRequest.getService().getDataByType(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String json = response.body().string();
                    Log.e("-----------", "按月查询数据返回：" + json);
                    heartRate = JsonManager.parseJson(json, HeartRate.class);
                    updateUI(heartRate);

                } catch (Exception e) {
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });


    }

    private String getDataTime() {
        if (month >= 10) {
            return years + "-" + month;
        } else {
            return years + "-0" + month;
        }
    }

    private void updateUI(HeartRate heartRate) {
        List<HealthData> ls = new ArrayList<>();
        //添加当月的天数
        int days = 0;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                days = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            case 2:
                if (years % 4 == 0) {
                    days = 29;
                } else {
                    days = 28;
                }
                break;
        }

        for (int i = 1; i < days + 1; i++) {
            HealthData data = new HealthData();
            data.setTag(1);
            data.setDay(String.valueOf(i));
            data.setMonth(String.valueOf(month));
            ls.add(data);
        }

        for (HealthData data : ls) {
            for (HeartRate.DataBean.ResultBean resultBean : heartRate.getData().getResult()) {
                String sd = DateFormatUtil.forString(resultBean.getDate(), "dd");
                if (data.getDay().length() > 1) {
                    if (sd.equals(data.getDay())) {
                        data.setTag(2);
                        data.setInstrument(resultBean.getInstrument());
                        data.setTime1(DateFormatUtil.forString(resultBean.getDate(), "HH:mm"));
                        data.setValue(resultBean.getValue());
                        data.setUnit(resultBean.getUnit());
                        data.setDiseasestate(resultBean.getDiseasestate());
                        data.setDiseasestate_describe(resultBean.getDiseasestate_describe());
                    }
                } else {
                    if (sd.equals("0" + data.getDay())) {
                        data.setTag(2);
                        data.setInstrument(resultBean.getInstrument());
                        data.setTime1(DateFormatUtil.forString(resultBean.getDate(), "HH:mm"));
                        data.setValue(resultBean.getValue());
                        data.setUnit(resultBean.getUnit());
                        data.setDiseasestate(resultBean.getDiseasestate());
                        data.setDiseasestate_describe(resultBean.getDiseasestate_describe());
                    }
                }

            }

        }

        //判断当月的第一天是星期几
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = sdf.parse(years + "-" + month + "-01");//年月日格式的日期
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        Log.e("---------", "周几" + w);
        list.clear();
        switch (w) {
            case 0://周日
                list.addAll(ls);
                break;
            case 1://周一：需要增加1天的上月的数据

                getOnMonth(1, month, years);
                list.addAll(ls);
                break;
            case 2://周二
                getOnMonth(2, month, years);
                list.addAll(ls);
                break;
            case 3://周三
                getOnMonth(3, month, years);
                list.addAll(ls);
                break;
            case 4://周四
                getOnMonth(4, month, years);
                list.addAll(ls);
                break;
            case 5://周五
                getOnMonth(5, month, years);
                list.addAll(ls);
                break;
            case 6://周六
                getOnMonth(6, month, years);
                list.addAll(ls);
                break;
        }


        //计算最后一天是周几增下一月的天数
        Date date2;
        try {
            date2 = sdf.parse(years + "-" + month + "-" + ls.get(ls.size() - 1).getDay());//年月日格式的日期
            cal.setTime(date2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w2 = cal.get(Calendar.DAY_OF_WEEK) - 1;
        switch (w2) {
            case 0://周日
                addToDay(6);
                break;
            case 1://周一：需要增加1天的上月的数据
                addToDay(5);
                break;
            case 2://周二
                addToDay(4);
                break;
            case 3://周三
                addToDay(3);
                break;
            case 4://周四
                addToDay(2);
                break;
            case 5://周五
                addToDay(1);
                break;
            case 6://周六

                break;
        }

        for (HealthData data : list) {
            String sd = DateFormatUtil.forString(DateFormatUtil.getTime(), "dd");
            if (data.getDay().length() > 1) {
                if (data.getDay().equals(sd)) {
                    data.setSelect(1);
                    upDataValue(data);
                    break;
                }
            } else {
                if (("0" + data.getDay()).equals(sd)) {
                    data.setSelect(1);
                    upDataValue(data);
                    break;
                }
            }

        }

        adapter.notifyDataSetChanged();
    }

    private void upDataValue(HealthData data) {
        data_info_1.setVisibility(View.GONE);
        data_info_2.setVisibility(View.GONE);
        for (HeartRate.DataBean.ResultBean resultBean : heartRate.getData().getResult()) {
            String sd = DateFormatUtil.forString(resultBean.getDate(), "dd");
            if (data.getDay().length() > 1) {
                if (sd.equals(data.getDay())) {
                    Log.e("--------", "sd:" + sd);
                    Log.e("*********", "data:" + data.getDay());
                    Log.e("xxxxxxxxxxxxxxxx", "data.getInstrument():" + data.getInstrument());
                    if (resultBean.getInstrument().equals("1")) {
                        data_info_1.setVisibility(View.VISIBLE);
                        select_data = resultBean;
                        value.setText(resultBean.getValue());
                        unit.setText(resultBean.getUnit());
                        time.setText(DateFormatUtil.forString(resultBean.getDate(), "HH:mm"));
                    } else if (resultBean.getInstrument().equals("2")) {
                        data_info_2.setVisibility(View.VISIBLE);
                        select_dat2 = resultBean;
                        value2.setText(resultBean.getValue());
                        unit2.setText(resultBean.getUnit());
                        time2.setText(DateFormatUtil.forString(resultBean.getDate(), "HH:mm"));
                    } else {
                        data_info_1.setVisibility(View.VISIBLE);
                        select_data = resultBean;
                        value.setText(resultBean.getValue());
                        unit.setText(resultBean.getUnit());
                        time.setText(DateFormatUtil.forString(resultBean.getDate(), "HH:mm"));
                    }

                }
            } else {
                if (sd.equals("0" + data.getDay())) {
                    Log.e("--------", "sd:" + sd);
                    Log.e("*********", "data:" + data.getDay());
                    Log.e("xxxxxxxxxxxxxxxx", "data.getInstrument():" + data.getInstrument());
                    if (resultBean.getInstrument().equals("1")) {
                        data_info_1.setVisibility(View.VISIBLE);
                        select_data = resultBean;
                        value.setText(resultBean.getValue());
                        unit.setText(resultBean.getUnit());
                        time.setText(DateFormatUtil.forString(resultBean.getDate(), "HH:mm"));
                    } else if (resultBean.getInstrument().equals("2")) {
                        data_info_2.setVisibility(View.VISIBLE);
                        select_dat2 = resultBean;
                        value2.setText(resultBean.getValue());
                        unit2.setText(resultBean.getUnit());
                        time2.setText(DateFormatUtil.forString(resultBean.getDate(), "HH:mm"));
                    } else {
                        data_info_1.setVisibility(View.VISIBLE);
                        select_data = resultBean;
                        value.setText(resultBean.getValue());
                        unit.setText(resultBean.getUnit());
                        time.setText(DateFormatUtil.forString(resultBean.getDate(), "HH:mm"));
                    }

                }
            }

        }
    }

    private void addToDay(int num) {
        for (int i = 0; i < num; i++) {
            HealthData data = new HealthData();
            data.setTag(0);
            data.setDay(String.valueOf(i + 1));
            list.add(data);
        }
    }

    /**
     * 计算上一个月份最后一天是几号，并且增加指定的天数
     *
     * @param num：增加上一个有天数数量
     * @param month：当前的月份
     * @param years：年份
     */
    private void getOnMonth(int num, int month, int years) {
        Log.e("---------", "当月:" + month);
        //上一月的最后一天
        int on_month_day = 0;
        switch (month) {
            case 1:
                on_month_day = 30;
                break;
            case 12:
                on_month_day = 31;
                break;
            case 11:
                on_month_day = 31;
                break;
            case 10:
                on_month_day = 30;
                break;
            case 9:
                on_month_day = 31;
                break;
            case 8:
                on_month_day = 31;
                break;
            case 7:
                on_month_day = 30;
                break;
            case 6:
                on_month_day = 31;
                break;
            case 5:
                on_month_day = 30;
                break;
            case 4:
                on_month_day = 31;
                break;
            case 3:
                if (years % 4 == 0) {
                    on_month_day = 29;
                } else {
                    on_month_day = 28;
                }

                break;
            case 2:
                on_month_day = 31;
                break;

        }

        for (int i = 0; i < num; i++) {
            HealthData data = new HealthData();
            data.setTag(0);
            data.setDay(String.valueOf((on_month_day--)));
            list.add(data);
        }
        //list需要再倒排序一下
        Collections.reverse(list);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        HealthData data = list.get(position);
        if (data.getTag() >= 2) {
            //是当月的天数并且有数据
            for (HealthData d : list) {
                d.setSelect(0);
            }
            data.setSelect(1);
            adapter.notifyDataSetChanged();
            upDataValue(data);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.data_info_1) {
            try {
                final HeartRateActivity activity = (HeartRateActivity) getActivity();
                HealthDataInfoActivit.start(getContext(), select_data.getValue(), select_data.getUnit(), select_data.getDiseasestate(), activity.health.getName(), select_data.getSuggest());
            } catch (Exception e) {
            }
        } else if (v.getId() == R.id.data_info_2) {
            try {
                final HeartRateActivity activity = (HeartRateActivity) getActivity();
                HealthDataInfoActivit.start(getContext(), select_dat2.getValue(), select_dat2.getUnit(), select_dat2.getDiseasestate(), activity.health.getName(), select_data.getSuggest());
            } catch (Exception e) {
            }
        } else if (v.getId() == R.id.left) {
            //查询上一月的数据
            if (month > 1) {
                month--;
                Get();
            } else {
                month = 12;
                years--;
                Get();
            }

        } else if (v.getId() == R.id.right) {
            //查询下一月数据
            if (month < 12) {
                month++;
                Get();
            } else {
                month = 1;
                years++;
                Get();
            }
        }
    }
}
